package com.hisense.ovcloud.mqtt.business;

import com.hisense.ovcloud.mqtt.business.service.MQTTClientConnector;
import com.mybatisflex.core.query.QueryWrapper;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.reactive.config.EnableWebFlux;


@SpringBootApplication(scanBasePackages={
        "com.hisense.ovcloud.commons",
        "com.hisense.ovcloud.mqtt.business",
        "com.hisense.ovcloud.commons.configs",
        "com.hisense.ovcloud.commons.configs.*",
        "com.hisense.ovcloud.commons.configs.*.*"
})
@EnableWebFlux
@EnableAsync
@EnableEncryptableProperties
@EnableTransactionManagement
@ComponentScan(basePackages = {
        "com.hisense.ovcloud.commons",
        "com.hisense.ovcloud.mqtt.business",
        "com.hisense.ovcloud.commons.configs",
        "com.hisense.ovcloud.commons.configs.*",
        "com.hisense.ovcloud.commons.configs.*.*"})
@MapperScan("com.hisense.ovcloud.mqtt.business.mapper")
@Slf4j
public class Main implements CommandLineRunner {

    @Value("${mqtt.client.waitSecondsForMqttConnCheckAfterStartup:30}")
    private int waitSecondsForMqttConnCheckAfterStartup;

    @Value("${mqtt.client.checkIntervalSeconds:30}")
    private int checkIntervalSeconds;

    private final MQTTClientConnector mqttClientConnector;

    public Main(MQTTClientConnector mqttClientConnector) {
        this.mqttClientConnector = mqttClientConnector;
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Override
    public void run(String... args){
        try {
            Thread.sleep( waitSecondsForMqttConnCheckAfterStartup * 1000L);
            log.info("start to check mqtt connection status.");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        mqttClientConnector.reconnect(checkIntervalSeconds);
    }

    @Bean
    @Primary
    public Validator springValidator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    @Primary
    public QueryWrapper queryWrapper(){
        return QueryWrapper.create();
    }

}
